package com.verification.code.controller;

import com.verification.code.utils.Base64ImageCodeUtil;
import com.verification.code.utils.ImageVerifyCodeUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;

/**
 * @Author 尚智江
 * @description
 * @CreateDate 2023/11/11 23:05
 */

@RestController
@CrossOrigin
public class CodeController {

    @GetMapping("/image")
    public void verifyCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 生成验证码图片
        Map<String, Object> imageVerifyCode = ImageVerifyCodeUtil.generate();
        BufferedImage bfm = (BufferedImage) imageVerifyCode.get("image");
        String code = String.valueOf(imageVerifyCode.get("code"));
        HttpSession session = request.getSession();
        session.setAttribute("verifyCode", code);
        // 使用 ImageIO工具类将 图片验证码输出到响应流
        ImageIO.write(bfm, "PNG", response.getOutputStream());
    }
    @GetMapping("/image1")
    public Map<String, Object> generateVerifyCode() {
        return Base64ImageCodeUtil.generate();
    }
}
